package cn.practice.chat.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.map.MapUtil;
import cn.practice.chat.lang.Result;
import cn.practice.chat.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@Slf4j
@RestController
public class CaptchaController {

    public final static String CAPTCHA_KEY = "captcha";

    @Autowired
    RedisUtil redisUtil;

    @GetMapping("/captcha")
    public Result captcha() {
        String key = UUID.randomUUID().toString();
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(160, 60);
        String code = circleCaptcha.getCode();
        log.info("code={}",circleCaptcha.getCode());
        String base64Img = circleCaptcha.getImageBase64Data();
        redisUtil.hset(CAPTCHA_KEY, key, code,120);
        return Result.success(MapUtil.builder()
                .put("token", key)
                .put("captchaImg", base64Img)
                .build());
    }

}